package com.mes.cloud.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mes.cloud.api.dto.request.product.ProductCompetitiveBrandAddRequest;
import com.mes.cloud.api.dto.request.product.ProductCompetitiveBrandEnableRequest;
import com.mes.cloud.api.dto.request.product.ProductCompetitiveBrandPageRequest;
import com.mes.cloud.api.dto.response.product.ProductCompetitiveBrandPageDto;
import com.mes.cloud.exception.BaseException;
import com.mes.cloud.common.CommPager;
import com.mes.cloud.common.JsonResult;
import com.mes.cloud.constant.Constants;
import com.mes.cloud.dao.BaseAreaDao;
import com.mes.cloud.dao.ProductCompetitiveBrandDao;
import com.mes.cloud.entity.BaseArea;
import com.mes.cloud.entity.ProductCompetitiveBrand;
import com.mes.cloud.entity.ProductLog;
import com.mes.cloud.entity.vo.product.ProductCompetitiveBrandPageVo;
import com.mes.cloud.enums.HttpStatusEnum;
import com.mes.cloud.util.CommonUtil;
import com.mes.cloud.util.DateUtil;
import com.mes.cloud.util.UserUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * 对标竞品关联
 *
 * @author xy
 * @version 2019-08-21 16:12:50
 * @email yuan.xue3@pactera.com
 */
@SuppressWarnings("JavaDoc")
@Service
public class ProductCompetitiveBrandService {

    private ProductCompetitiveBrandDao productCompetitiveBrandDao;

    private IPKeyGenerator ipKeyGenerator;

    private LogService logService;

    private BaseAreaDao baseAreaDao;

    @SuppressWarnings("SpringJavaAutowiringInspection")
    @Autowired
    public ProductCompetitiveBrandService(ProductCompetitiveBrandDao productCompetitiveBrandDao
            , IPKeyGenerator ipKeyGenerator
            , LogService logService, BaseAreaDao baseAreaDao) {
        this.productCompetitiveBrandDao = productCompetitiveBrandDao;
        this.ipKeyGenerator = ipKeyGenerator;
        this.logService = logService;
        this.baseAreaDao = baseAreaDao;
    }

    /**
     * <分页查列表>
     *
     * @param pageRequest
     * @return JsonResult<CommPager<ProductCompetitiveBrandPageDto>>
     * @author xy
     * @date 2019/8/28 15:12
     */
    public JsonResult<CommPager<ProductCompetitiveBrandPageDto>> pageList(ProductCompetitiveBrandPageRequest pageRequest) {
        Page<ProductCompetitiveBrandPageDto> page = PageHelper.startPage(pageRequest.getCurrentPage(), pageRequest.getPageSize());
        //查询条件
        pageRequest.setEnableFlag(Constants.ENABLE_FLAG_YES);
        List<ProductCompetitiveBrandPageVo> productCompetitiveBrandList = productCompetitiveBrandDao.pageList(pageRequest);
        List<ProductCompetitiveBrandPageDto> productCompetitiveBrandDtoList = new ArrayList<>();
        for (ProductCompetitiveBrandPageVo productCompetitiveBrand : productCompetitiveBrandList) {
            // 设置行政区划全名
            BaseArea baseArea = baseAreaDao.selectByPrimaryKey(productCompetitiveBrand.getAreaId());
            if(Objects.nonNull(baseArea)){
                String areaFullName = baseAreaDao.getAreaFullName(baseArea.getParentGroup() + "," + baseArea.getId());
                productCompetitiveBrand.setAreaName(areaFullName);
            }
            ProductCompetitiveBrandPageDto productCompetitiveBrandDto = new ProductCompetitiveBrandPageDto();
            BeanUtils.copyProperties(productCompetitiveBrand, productCompetitiveBrandDto);
            productCompetitiveBrandDtoList.add(productCompetitiveBrandDto);
        }

        CommPager<ProductCompetitiveBrandPageDto> pageResult = new CommPager<>(page, productCompetitiveBrandDtoList);
        JsonResult<CommPager<ProductCompetitiveBrandPageDto>> jsonResult = new JsonResult<>();
        jsonResult.setMsg(HttpStatusEnum.OK.getMessage()).setCode(HttpStatusEnum.OK.getCode()).setData(pageResult);

        return jsonResult;
    }

    /**
     * <新增>
     *
     * @param productCompetitiveBrandRequest
     * @return JsonResult
     * @author xy
     * @date 2019/8/28 15:12
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult add(ProductCompetitiveBrandAddRequest productCompetitiveBrandRequest) {
        //提交数据与已存在数据检查
        areaRepeatCheck(productCompetitiveBrandRequest);

        JsonResult jsonResult = new JsonResult();
        //如果新增区域id数组大小等于0，数据无变动无需修改数据
        if (CollectionUtils.isEmpty(productCompetitiveBrandRequest.getAreaIds())) {
            jsonResult.setMsg(HttpStatusEnum.OK.getMessage()).setCode(HttpStatusEnum.OK.getCode());
            return jsonResult;
        }

        List<ProductCompetitiveBrand> addList = new ArrayList<>();
        List<String> areaIds = productCompetitiveBrandRequest.getAreaIds();
        List<String> areaNames = productCompetitiveBrandRequest.getAreaNames();

        for (int i = 0; i < areaIds.size(); i++) {
            ProductCompetitiveBrand productCompetitiveBrand = new ProductCompetitiveBrand();
            BeanUtils.copyProperties(productCompetitiveBrandRequest, productCompetitiveBrand);
            productCompetitiveBrand.setId(ipKeyGenerator.getGenerateKey());
            productCompetitiveBrand.setAreaId(areaIds.get(i));
            productCompetitiveBrand.setAreaName(areaNames.get(i));
            productCompetitiveBrand.setUpdateDateStr(DateUtil.updateDateStr());
            productCompetitiveBrand.setCreateBy(UserUtil.getCreateByName());
            productCompetitiveBrand.setUpdateBy(UserUtil.getUpdateByName());
            productCompetitiveBrand.setCreateByNo(UserUtil.getCreateByNo());
            productCompetitiveBrand.setUpdateByNo(UserUtil.getUpdateByNo());
            addList.add(productCompetitiveBrand);
        }

        int count = productCompetitiveBrandDao.batchInsert(addList);
        if (count > 0) {
            for (ProductCompetitiveBrand pcb : addList) {
                this.insertLog(pcb.getProductId(), Constants.ADD_LINK_TO_COMPETITIVE_BRAND);
            }
            jsonResult.setMsg(HttpStatusEnum.OK.getMessage()).setCode(HttpStatusEnum.OK.getCode());
        } else {
            throw new BaseException(HttpStatusEnum.FAIL.getCode(),HttpStatusEnum.FAIL.getMessage());
        }

        return jsonResult;
    }

    /**
     * <区域重复检查>
     *
     * @param productCompetitiveBrandAddRequest
     * @author xy
     * @date 2019/8/28 15:23
     */
    private void areaRepeatCheck(ProductCompetitiveBrandAddRequest productCompetitiveBrandAddRequest) {

        String productId = productCompetitiveBrandAddRequest.getProductId();
        String relateProductId = productCompetitiveBrandAddRequest.getRelateProductId();

        ProductCompetitiveBrand queryParams = new ProductCompetitiveBrand();
        queryParams.setProductId(productId);
        queryParams.setRelateProductId(relateProductId);
        queryParams.setEnableFlag(Constants.ENABLE_FLAG_YES);

        //通过产品id与关联产品id 查询是否已存在产品关联数据
        List<ProductCompetitiveBrand> productCompetitiveBrandList = productCompetitiveBrandDao.select(queryParams);
        //存在关联数据
        if (!CollectionUtils.isEmpty(productCompetitiveBrandList)) {

            List<String> dbList = new ArrayList<>();
            List<String> requestList = new ArrayList<>();
            //db组合id与name
            for (ProductCompetitiveBrand productCompetitiveBrand : productCompetitiveBrandList) {
                String dbAreaId = productCompetitiveBrand.getAreaId();
                String dbAreaName = productCompetitiveBrand.getAreaName();
                String dbStr = dbAreaId + "," + dbAreaName;
                dbList.add(dbStr);
            }
            //请求组合id与name
            for (int i = 0; i < productCompetitiveBrandAddRequest.getAreaIds().size(); i++) {
                String requestAreaId = productCompetitiveBrandAddRequest.getAreaIds().get(i);
                String requestAreaName = productCompetitiveBrandAddRequest.getAreaNames().get(i);
                String requestStr = requestAreaId + "," + requestAreaName;
                requestList.add(requestStr);
            }

            //db list 转 set
            Set<String> dbSet = new HashSet<>(dbList);
            //请求 list 转 set
            Set<String> reqSet = new HashSet<>(requestList);
            //去重
            Set<String> set = CommonUtil.deleteExistId(dbSet, reqSet);

            List<String> areaIds = new ArrayList<>();
            List<String> areaIdNames = new ArrayList<>();

            //提取岗位id与组织id
            for (String str : set) {
                String[] values = str.split(",");
                areaIds.add(values[0]);
                areaIdNames.add(values[1]);
            }

            productCompetitiveBrandAddRequest.setAreaIds(areaIds);
            productCompetitiveBrandAddRequest.setAreaNames(areaIdNames);

        }
    }

    /**
     * <更新状态>
     *
     * @param productCompetitiveBrandEnableRequest
     * @return JsonResult
     * @author xy
     * @date 2019/8/28 15:24
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult updateEnableFlag(ProductCompetitiveBrandEnableRequest productCompetitiveBrandEnableRequest) {
        JsonResult jsonResult = new JsonResult();

        productCompetitiveBrandEnableRequest.setEnableFlag(Constants.ENABLE_FLAG_NO);
        productCompetitiveBrandEnableRequest.setUpdateDateStr(DateUtil.updateDateStr());
        productCompetitiveBrandEnableRequest.setUpdateBy(UserUtil.getUpdateByName());
        productCompetitiveBrandEnableRequest.setUpdateByNo(UserUtil.getUpdateByNo());

        int count = productCompetitiveBrandDao.batchUpdateEnable(productCompetitiveBrandEnableRequest);
        if (count > 0) {
            // 插入操作日志
            for (String id : productCompetitiveBrandEnableRequest.getIds()) {
                this.insertLog(productCompetitiveBrandEnableRequest.getProductId(), Constants.REMOVE_LINK_TO_COMPETITIVE_BRAND);
            }
            jsonResult.setMsg(HttpStatusEnum.OK.getMessage());
            jsonResult.setCode(HttpStatusEnum.OK.getCode());
        } else {
            throw new BaseException(HttpStatusEnum.FAIL.getCode(),HttpStatusEnum.FAIL.getMessage());
        }
        return jsonResult;
    }

    /**
     * <日志>
     *
     * @param id,logMessage
     * @author xy
     * @date 2019/8/28 15:24
     */
    @SuppressWarnings("Duplicates")
    private void insertLog(String id, String logMessage) {
        ProductLog productLog = new ProductLog();
        productLog.setProductId(id);
        productLog.setMenuCode(Constants.PRODUCT_MENU_CODE);
        productLog.setLog(logMessage);
        productLog.setId(ipKeyGenerator.getGenerateKey());
        productLog.setUpdateDateStr(DateUtil.updateDateStr());
        productLog.setCreateBy(UserUtil.getCreateByName());
        productLog.setUpdateBy(UserUtil.getUpdateByName());
        productLog.setCreateByNo(UserUtil.getCreateByNo());
        productLog.setUpdateByNo(UserUtil.getUpdateByNo());
        logService.insertProductLog(productLog);
    }

}
